package com.aispeech.task.api.controller.base;

import com.aispeech.task.api.config.WebSecurityConfig;
import com.aispeech.task.api.data.domain.SysUser;
import com.aispeech.task.api.utils.JwtTokenUtil;
import com.aispeech.task.common.data.enums.APICode;
import com.aispeech.task.common.data.vo.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class Auth extends Base {
    @Autowired
    @Qualifier("passwordEncoderBean")
    PasswordEncoder passwordEncoder;
    @Autowired
    @Qualifier("jwtUserDetailsService")
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping(WebSecurityConfig.AUTH_PATH)
    public Result<SysUser> auth(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        final UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        if (userDetails != null && passwordEncoder.matches(password, userDetails.getPassword())) {
            final String token = jwtTokenUtil.generateToken(userDetails);

            SysUser user = SysUser.of("", username, "Admin");
            user.setToken(token);

            return Result.ok(user);
        } else {
            return Result.fail(APICode.BAD_CREDENTIALS);
        }
    }
}
